package com.ruoyi.manager.controller;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.manager.domain.UserDto;
import com.ruoyi.manager.properties.JwtProperties;
import com.ruoyi.manager.utils.JwtUtil;
import com.wf.captcha.SpecCaptcha;
import io.jsonwebtoken.Claims;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.manager.domain.Member;
import com.ruoyi.manager.service.IMemberService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * memberController
 * 
 * @author ruoyi
 * @date 2025-08-12
 */
@RestController
@RequestMapping("/manager/member")
public class MemberController extends BaseController
{
    @Autowired
    private IMemberService memberService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    @Qualifier("userRedisTemplate")
    private RedisTemplate<String , Object> redisTemplate;

    /**
     * 查询member列表
     */
    @PreAuthorize("@ss.hasPermi('manager:member:list')")
    @GetMapping("/list")
    public TableDataInfo list(Member member)
    {
        startPage();
        List<Member> list = memberService.selectMemberList(member);
        return getDataTable(list);
    }

    /**
     * 导出member列表
     */
    @PreAuthorize("@ss.hasPermi('manager:member:export')")
    @Log(title = "member", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Member member)
    {
        List<Member> list = memberService.selectMemberList(member);
        ExcelUtil<Member> util = new ExcelUtil<Member>(Member.class);
        util.exportExcel(response, list, "member数据");
    }

    /**
     * 获取member详细信息
     */
    @PreAuthorize("@ss.hasPermi('manager:member:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(memberService.selectMemberById(id));
    }

    /**
     * 新增member
     */
    @PreAuthorize("@ss.hasPermi('manager:member:add')")
    @Log(title = "member", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Member member)
    {
        return toAjax(memberService.insertMember(member));
    }

    /**
     * 修改member
     */
    @PreAuthorize("@ss.hasPermi('manager:member:edit')")
    @Log(title = "member", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Member member)
    {
        return toAjax(memberService.updateMember(member));
    }

    /**
     * 删除member
     */
    @PreAuthorize("@ss.hasPermi('manager:member:remove')")
    @Log(title = "member", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(memberService.deleteMemberByIds(ids));
    }


    /**
     * 用户登录
     */
    @PostMapping("login")
    public AjaxResult login(@RequestBody UserDto user){
        System.out.println(user);

        //验证码校验
//        String correct = (String) redisTemplate.opsForValue().get("captcha");
//        if (!user.getCode().equals(correct)) {
//            return AjaxResult.warn("验证码不正确");
//        }

        if(StringUtil.isNullOrEmpty(user.getPassword()) || StringUtil.isNullOrEmpty(user.getPhone())){
            return AjaxResult.warn("用户名或密码不能为空");
        }
        Member member = memberService.login(user.getPhone(), user.getPassword());
        if(member == null){
            return AjaxResult.warn("用户名或密码错误");
        }

        //添加token
        Map<String,Object> claims = new HashMap<>();
        claims.put("memberId" , member.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        System.out.println(token);
        Map<String , Object> res = new HashMap<>();

        res.put("token" , token);
        res.put("member" , member);

        return AjaxResult.success(res);
    }



    @GetMapping("/captcha")
    public void captcha(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        SpecCaptcha captcha = new SpecCaptcha(140, 40, 4);
        resp.setContentType("image/gif");
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);

        //req.getSession().setAttribute("captcha", captcha.text().toLowerCase());
        redisTemplate.opsForValue().set("captcha",
                captcha.text().toLowerCase(), Duration.ofMinutes(3));


        captcha.out(resp.getOutputStream());
    }

}
